//
//  ScrollLabel.m
//  test
//
//  Created by BH on 16/3/2.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "ScrollLabel.h"

@interface ScrollLabel ()<UIScrollViewDelegate>

@property(nonatomic,assign)NSInteger count;

@end

@implementation ScrollLabel

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

-(void)addLabelWithText:(NSArray*)array duration:(CGFloat)duration
{
    self.count = array.count;
    
    //添加最后一个label
    UILabel *lastLab = [[UILabel alloc] init];
    lastLab.text = [array lastObject];
    lastLab.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self addSubview:lastLab];
    
    //添加中间的label
    for (int i=0; i<array.count; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, i*self.frame.size.height+self.frame.size.height, self.frame.size.width, self.frame.size.height)];
        label.text = array[i];
        [self addSubview:label];
    }
    
    //添加第一个label
    UILabel *firstLab = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height*(array.count+1), self.frame.size.width, self.frame.size.height)];
    firstLab.text = [array firstObject];
    [self addSubview:firstLab];
    
    //设置scrollview
    self.contentSize = CGSizeMake(self.frame.size.width, self.frame.size.height*(array.count+2));
    self.contentOffset = CGPointMake(0, 0);
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    [self scrollRectToVisible:CGRectMake(0, self.frame.size.height, self.frame.size.width, self.frame.size.height) animated:YES];

    //循环滚动计时器
    [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(handleScroll:) userInfo:nil repeats:YES];
}

-(void)handleScroll:(NSTimer *)timer
{
    CGPoint pt = self.contentOffset;
    if (pt.y == self.frame.size.height*self.count) {
        [self setContentOffset:CGPointMake(0, 0)];
        [self scrollRectToVisible:CGRectMake(0, self.frame.size.height, self.frame.size.width, self.frame.size.height) animated:YES];
    }else{
        [self scrollRectToVisible:CGRectMake(0, pt.y+self.frame.size.height, self.frame.size.width, self.frame.size.height) animated:YES];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int currentPage = floor((self.contentOffset.y-self.frame.size.height/(self.count+2))/self.frame.size.height)+1;
    if (currentPage == 0) {
        //如果是第一个，显示最后一页
        [self scrollRectToVisible:CGRectMake(0, self.frame.size.height*self.count, self.frame.size.width, self.frame.size.height) animated:YES];
    }else if (currentPage == self.count+1){
        //如果是最后+1，就开始循环第一个
        [self scrollRectToVisible:CGRectMake(0, self.frame.size.height, self.frame.size.width, self.frame.size.height) animated:YES];
    }
}

@end
